In this tutorial, i would like to share with you how to build restful api in laravel 5.5 application. Here i will share with you create basic and simple resource api route with json response. you can simply use with your big project, you can make basic setup for you application.
Before start i would like to recommend following link for authentication api : Laravel 5 – How to create API Authentication using Passport ?. Here i explained how to create api authentication, so you can make authentication apis with posts restful api.
In this example i will create posts table and create rest api of posts with resource route. Here i also attach screen shot for all resource route response, so you can check response for GET, POST, PUT and DELETE for list, create, update and delete. So let’s just follow bellow step and you will get best api platform.
1) List: Verb:GET, URL:http://localhost:8000/api/posts
2) Create: Verb:POST, URL:http://localhost:8000/api/posts
3) Show: Verb:GET, URL:http://localhost:8000/api/posts/{id}
4) Update: Verb:PUT, URL:http://localhost:8000/api/posts/{id}
5) Delete: Verb:DELETE, URL:http://localhost:8000/api/posts/{id}
Step 1 : Install Laravel 5.5 App
we are going to from scratch so, we need to get fresh Laravel 5.5 application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Create Post Table and Model
next, we require to create migration for posts table using Laravel 5.5 php artisan command, so first fire bellow command:
php artisan make:migration create_posts_table
After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create posts table.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
After create “posts” table you should create Item model for posts, so first create file in this path app/Post.php and put bellow content in item.php file:
app/Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'name', 'description',
];
}
Step 3: Create Rest API Route
In this is step we should create resource routes for list, create, update and delete. so open your routes/api.php file and add following route.
routes/api.php
Route::resource('posts', 'API\PostAPIController');
Step 4: Create Controllers
in next step, now we have create new controller as APIBaseController and PostAPIController, i created new folder “API” in Controllers folder because we will make alone APIs controller, So let’s create both controller:
app/Http/Controllers/API/APIBaseController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;
class APIBaseController extends Controller
{
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
app/Http/Controllers/API/PostAPIController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\APIBaseController as APIBaseController;
use App\Post;
use Validator;
class PostAPIController extends APIBaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return $this->sendResponse($posts->toArray(), 'Posts retrieved successfully.');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
$validator = Validator::make($input, [
'name' => 'required',
'description' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$post = Post::create($input);
return $this->sendResponse($post->toArray(), 'Post created successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
if (is_null($post)) {
return $this->sendError('Post not found.');
}
return $this->sendResponse($post->toArray(), 'Post retrieved successfully.');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = $request->all();
$validator = Validator::make($input, [
'name' => 'required',
'description' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$post = Post::find($id);
if (is_null($post)) {
return $this->sendError('Post not found.');
}
$post->name = $input['name'];
$post->description = $input['description'];
$post->save();
return $this->sendResponse($post->toArray(), 'Post updated successfully.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
if (is_null($post)) {
return $this->sendError('Post not found.');
}
$post->delete();
return $this->sendResponse($id, 'Tag deleted successfully.');
}
}
Now simply you can run above listed url like as bellow screen shot:
Post List API:
Post Create API:
Post Show API:
Post Update API:
Post Delete API:
I hope it can help you…